'use strict'

process.chdir(__dirname) 

const titbit = require('titbit')
const fs = require('fs')
const pg =require('pg')
const dbconfig = require('./dbconfig.js')

let psql = new pg.Pool(dbconfig)

try{
    fs.accessSync('./images')
}catch{
    fs.mkdirSync('./images')
}

let cert_path ='/usr/local/share'


const app = new titbit({
    debug:true,
    globalLog:true,
    cert:`${cert_path}/api.vvh5.com.pem`,
    key:`${cert_path}/api.vvh5.com.key`
})
app.get('/content',async c =>{
    let sqltext = 'SELECT id,title,update_time FROM content'
    let r = await psql.query(sqltext)

    c.send(r.rows)
})
app.get('/upload',async c =>{
    await c.helper.pipe('./upload.html',c.replyn)
})

app.post('/upload',async()=>{
    let f = c.getFile('file')

    if(!f){
        return c.status(400).send('file not found')
    }
     
    let fname = c.helper.makeName(f.filename)

    try{
        await c.moveFile(f,`./images/${fname}`)

        c.send(fname)
    }catch(err){
        c.status(500).send('failed')
    }
    })
    app.get('/image/:name',async c=>{
        let imgname = c.param.name

        try{
            await c.helper.pipe(`./images/${imgname}`,c.reply)
        } catch(err){
            c.status(404).se('image not found')

        }
        app.get('')
    })
app.run(1100)